package br.eb.ime.maps;

import java.io.IOException;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import com.sun.lwuit.Button;
import com.sun.lwuit.ComboBox;
import com.sun.lwuit.Command;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;

public class MidMap extends MIDlet implements ActionListener{

	private Display display;
	private Form fmMain, fmMapa;
	private GoogleMaps gMap;
	private int zoom = 2;
	private double lon, lat;
	private String tipoMapa;
	private String msg = "Mensagem";

	//Declara��o de bot�es
	private Command cmPesquisar;
	private Command cmOut;
	private Command cmSair;
	private Command cmVoltar;

	//Declara��o da Combo
	private ComboBox cbTipo;

	//Declara��o do TextField
	private TextField tfCidade, tfPais;

	//Declara��o de Labels
	private Label lCidade, lPais, lTipo;

	public MidMap() {
		// TODO Auto-generated constructor stub
		System.out.println("Entrei no construtor MidMap()...");

		Display.init(this);

		try {
			  Resources r = Resources.open("/javaTeste.res");
			  UIManager.getInstance().setThemeProps(r.getTheme("javaTheme"));
			} catch (IOException ioe) {
				ioe.printStackTrace();
			  System.out.println("Couldn't load theme.");
			}

		//Inicializa��o dos bot�es
		cmPesquisar = new Command("Pesquisar");
		cmSair = new Command("Sair");
		cmOut = new Command("Sair");
		cmVoltar = new Command("Voltar");

		//Inicializa��o de Combo
		cbTipo = new ComboBox();
		cbTipo.addItem("Normal");
		cbTipo.addItem("Satelite");
		cbTipo.addItem("Hibrido");

		//Inicializa��o de TextField
		tfCidade = new TextField();
		tfPais = new TextField();

		//Inicializa��o de labels
		lCidade = new Label("Cidade: ");
		lPais = new Label("Pais: ");
		lTipo = new Label("Selecione o tipo de mapa: ");

		//Inicializa��o do fmMain
		fmMain = new Form("Consulte");

		fmMain.setLayout(new BorderLayout());

		fmMain.setLayout(new BoxLayout(BoxLayout.Y_AXIS));

		fmMain.addCommand(cmSair);
		fmMain.addCommand(cmPesquisar);

		fmMain.addComponent(lPais);
		fmMain.addComponent(tfPais);

		fmMain.addComponent(lCidade);
		fmMain.addComponent(tfCidade);

		fmMain.addComponent(lTipo);
		fmMain.addComponent(cbTipo);

		fmMain.setCommandListener(this);

		//Constru��o do fmMapa
		fmMapa = new Form("Mapa"){
		public void keyPressed(int keyCode){
			int game = Display.getInstance().getGameAction(keyCode);
			double sub = 0.5d;
			switch (game) {
			case Display.GAME_FIRE:
				if(++zoom <= 17)
					getImagem(lon, lat, zoom, tipoMapa);
				else
					--zoom;
				break;
			case Display.GAME_UP:
				getImagem(lon, lat = movPositivo(zoom, lat), zoom, tipoMapa);
				break;
			case Display.GAME_DOWN:
				getImagem(lon, lat = movNegativo(zoom, lat), zoom, tipoMapa);
				break;
			case Display.GAME_LEFT:
				getImagem(lon = movNegativo(zoom, lon), lat, zoom, tipoMapa);
				break;
			case Display.GAME_RIGHT:
				getImagem(lon = movPositivo(zoom, lon), lat, zoom, tipoMapa);
				break;
			default:
				break;
			}
			super.keyPressed(keyCode);
			}
		};

		fmMapa.addCommand(cmOut);
		fmMapa.addCommand(cmVoltar);
		fmMapa.setCommandListener(this);
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		// TODO Auto-generated method stub

	}

	protected void pauseApp() {
		// TODO Auto-generated method stub

	}

	protected void startApp() throws MIDletStateChangeException {
		// TODO Auto-generated method stub
		fmMain.show();
	}

	public double movPositivo(int zoom, double coord){
		double dif1 = 2.0d;
		double dif2 = 0.5d;
		if(zoom > 0 && zoom <= 4){
			coord += dif1;
		}else if(zoom >= 5 && zoom <= 8){
			coord += dif1/3;
		}else{
			coord += dif2/248;
		}
		return coord;
	}

	public double movNegativo(int zoom, double coord){
		double dif1 = 2.0d;
		double dif2 = 0.5d;
		if(zoom > 0 && zoom <= 4){
			coord -= dif1;
		}else if(zoom >= 5 && zoom <= 8){
			coord -= dif1/3;
		}else{
			coord -= dif2/248;
		}
		return coord;
	}

	public void getImagem(double longit, double latit, int zoom, String tipo){
		Image map = null;
		try{
			if(tipo.equals("Normal")){
				map = gMap.getImageEstatica(225, 250, longit, latit, zoom, "bmp", "roadmap");
			}else if(tipo.equals("Satelite")){
				map = gMap.getImageEstatica(225, 250, longit, latit, zoom, "bmp", "satellite");
			}else if(tipo.equals("Hibrido")){
				map = gMap.getImageEstatica(225, 250, longit, latit, zoom, "bmp", "hybrid");
			}

			Container aux1 = new Container();
			Button aux2 = new Button(map);
			aux1.addComponent(aux2);
			fmMapa.addComponent(aux1);

			// Tratamento de inser��o e exibi��o da imagem no form
		}catch(Exception e){e.printStackTrace();}
	}

	public void ajuda(String msg){
		Dialog dlInfo = new Dialog("Alerta");
//		Tratamento do componente dialog
		TextArea txt = new TextArea(msg);
		dlInfo.addComponent(txt);
		dlInfo.addCommand(cmVoltar);
		dlInfo.show();
	}

	public void actionPerformed(ActionEvent ae){
		if(ae.getCommand() == cmPesquisar){
			System.out.println("Entrei no Command Pesquisar...");
			gMap = new GoogleMaps("ABQIAAAAUQtF1ptgmG6-YUjlHY7F1BTRERdeAiwZ9EeJWta3L_JZVS0bOBS655nHLpg1leI3dsP-2vBhtDGjQg");//Chave fornecida pela Google para a utiliza��o de sua API
			try{
				System.out.println("Entrei no try do Pesquisar...");
				if(tfCidade.getText().equals("") && tfPais.getText().equals("")){
					ajuda("Digite o nome da cidade ou pais que deseja pesquisar");
				}else{
					System.out.println("Vou usar o getGeocode...");
					new Thread(){
						public void run(){
							try{
								double[] geocodes = gMap.getGeocode(tfCidade.getText() + "," + tfPais.getText());
								System.out.println("Peguei o Geocode de dentro... e eigual a: " + geocodes[0] + " " + geocodes[1]);
								lat = geocodes[0];
								lon = geocodes[1];
							}catch(Exception e){e.printStackTrace();}

					System.out.println("Peguei o Geocode... e e igual a: " + lat + " " + lon);
					tipoMapa = (String) cbTipo.getSelectedItem();
					getImagem(lon, lat, zoom, tipoMapa);
//					ajuda(msg);
					System.out.println("Vou exibir o Form fmMapa...");
					fmMapa.show();
						}
				}.start();
				}
			}catch(Exception e){}
		}else if(ae.getCommand() == cmOut){
			getImagem(lon, lat, --zoom, tipoMapa);
		}else if(ae.getCommand() == cmVoltar){
			zoom = 8;
			fmMain.show();
		}else if(ae.getCommand() == cmSair)
		if(ae.getCommand() == cmSair)
			notifyDestroyed();
	}


}
